<template>
  <div class="app-container">
     <div class="switch-container">
        <el-switch
          :model-value="updateReminder"
          active-text="更新提醒"
          inactive-text="关闭提醒"
          @change="toggleUpdateReminder"
        ></el-switch>
      </div>
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane name="system">

        <template #label>
          系统消息
          <el-badge/>
        </template>

        <div class="messages-container">
          <div v-for="message in truncatedMessages" :key="message.id" class="message" @click="showDetail(message)">
            <el-badge :is-dot="message.unread" :offset="[-10,5]">
              <div class="message-header">
                <span>{{ message.date }}</span>
              </div>

              <div class="message-content">
                <span>{{ message.truncatedContent }}</span>
              </div>
            </el-badge>
          </div>
        </div>

      </el-tab-pane>
      
      <el-tab-pane name="updates" v-if="updateReminder">

        <template #label>
          更新通知
          <el-badge/>
        </template>

        <div class="messages-container">
          <div v-for="update in updates" :key="update.id" class="message" @click="showUpdateDetail(update)">
            <el-badge :is-dot="update.unread" :offset="[-10,5]">
              <div class="message-header">
                <span>{{ update.date }}</span>
              </div>
              <div class="message-content">
                  <span>您关注的书籍</span>
                  <span class="turnRed" @click="navigateToBook(update.book_id)">《{{ update.book_name }}》</span>
                  <span>更新了！</span>
                <span class="delete" @click.stop="confirmDelete(update.id)">删除</span>
              </div>
            </el-badge>
          </div>
        </div>

      </el-tab-pane>
    </el-tabs>

    <!-- 消息弹窗 -->
    <el-dialog v-model="showModal" width="50%" :before-close="beforeClose">
      <div class="dialog-content">
        <h3>{{ currentMessage?.date }}</h3>
        <p>{{ currentMessage?.xx }}</p>
      </div>
    </el-dialog>

  </div>
</template>

<script setup>
import { reactive, computed, ref, onMounted, getCurrentInstance } from 'vue';
import { user_systemMsg_recv, user_updateMsg_recv, user_deleteMsg } from '@/apis/user_IPC.js';
import { fetchBooks, books } from '@/apis/getBooks_by_tags.js';
import { useNavigation } from '@/utils/navigate.js';
import '@/display/fontTurnRed.css';


const { proxy } = getCurrentInstance();
const { navigateToCategory, navigateToBook, navigateToAuthor } = useNavigation(); //导入导航函数

const messages = reactive([]);
const updates = reactive([]);
const activeTab = ref('system');

const updateReminder = ref(localStorage.getItem('updateReminder')==="true");

// 切换提醒状态并更新 localStorage
const toggleUpdateReminder = () => {
  updateReminder.value = !updateReminder.value;
  localStorage.setItem('updateReminder', updateReminder.value);
};


//获取系统信息
const fetchMessages = async () => {
  try {
    const response = await user_systemMsg_recv(proxy);
    messages.splice(0, messages.length, ...response.data.system);
    messages.sort((a, b) => {
      return new Date(b.date) - new Date(a.date);
    });
  } catch (error) {
    console.error('Failed to fetch messages:', error);
  }
};

//获取书籍更新信息
const fetchUpdates = async () => {
  try {
    const response = await user_updateMsg_recv(proxy);

    const rawUpdates = response.data.update;
    await fetchBooks('all', proxy);

    // 重新映射 updates，添加 book_name 字段
    const updatedUpdates = rawUpdates.map(update => {
      const bookName = findBookNameById(update.book_id);
      return {
        ...update,
        book_name: bookName,
      };
    });
    updates.splice(0, updates.length, ...updatedUpdates);
    updates.sort((a, b) => {
      return new Date(b.date) - new Date(a.date);
    });
  } catch (error) {
    console.error('Failed to fetch updates:', error);
  }
};

// 辅助函数 findBookNameById
const findBookNameById = (bookId) => {
  const book = books.value.find(book => book.id === bookId);
  return book ? book.name : null;
};

//限制信息显示字数
const truncatedMessages = computed(() => {
  return messages.map(message => ({
    ...message,
    truncatedContent: message.xx.length > 60 ? message.xx.slice(0, 60) + '...' : message.xx
  }));
});

const showModal = ref(false);
const currentMessage = ref(null);

//查看信息
const showDetail = (message) => {
  const msgIndex = messages.findIndex(msg => msg.id === message.id);
  if (msgIndex !== -1) {
    messages[msgIndex].read = false;
  }
  currentMessage.value = message;
  showModal.value = true;
};

//关闭查看
const beforeClose = () => {
  showModal.value = false;
  currentMessage.value = null;
};

// 确认删除
const confirmDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这条消息吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    await user_deleteMsg(id, proxy);

    // 从本地数组中删除消息
    const messageIndex = messages.findIndex(message => message.id === id);
    if (messageIndex !== -1) {
      messages.splice(messageIndex, 1);
    }

    const updateIndex = updates.findIndex(update => update.id === id);
    if (updateIndex !== -1) {
      updates.splice(updateIndex, 1);
    }
  } catch {
    // 用户取消删除
  }
};

onMounted(() => {
  fetchMessages();
  fetchUpdates();
});

</script>

<style scoped>
.switch-container {
  position:absolute;
  top: 10px;
  right: 10px;
  z-index: 200;
}

.app-container {
  position: relative;
  width: 97%;
  height: 600px;
  margin-top: 2%;
  margin-left: auto;
  margin-right: auto;
  background-color: rgb(244, 245, 247);
  border-radius: 20px;
  border: 1px solid white;
  box-shadow: 2px 1px 19px rgba(0, 0, 0, 0.1);
}

.el-tabs {
  margin: 1%;
}

.el-tab-pane {
  background-color: white;
}

.messages-container {
  max-height: 500px; 
  width: 100%;
  overflow-y: auto;
}

.message {
  border-bottom: 1px solid #eee;
  padding: 20px;
}

.message:hover {
  cursor: pointer;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 15px;
  color: #666;
}

.message-content {
  margin-top: 10px;
  font-size: 16px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.el-badge{
  width: 100%;
}

.delete{
  position:absolute;
  right: 1%;
  bottom: 0.5%;
  cursor: pointer;
}

.dialog-content h3 {
  color: #d3d3d3; /* 淡灰色 */
  font-size: 16px; /* 根据需要调整大小 */
  text-align: left;
  margin: 0;
  padding: 10px; /* 根据需要调整间距 */
}

.dialog-content p {
  font-size: 18px; /* 比 h3 的字体大 */
  margin: 5px 0 0; /* 顶部留点空间 */
  padding: 0 10px; /* 与 h3 保持一致的水平间距 */
}
</style>